package net.cl.utils;

import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class BeanUtil {

	/**
	 * 复制bean的get属性到map
	 * 
	 * @param bean
	 * @return
	 */
	public static Map<String, Object> bean2Map(Object bean) {
		if (bean == null)
			throw new NullPointerException("bean");
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		Method[] ms = bean.getClass().getMethods();
		Method m = null;
		for (int i = 0; i < ms.length; i++) {
			m = ms[i];
			if (m != null && m.getName() != null && m.getName().length() > 3 && m.getName().startsWith("get")) {
				try {
					Object o = m.invoke(bean);
					map.put(StringUtil.firstLower(m.getName().substring(3)), o);
				} catch (Exception e) {
					// e.printStackTrace();
					continue;
				}
			}
		}
		return map;
	}

	public static String bean2Json(Object bean) {
		StringBuilder sb = new StringBuilder("{");
		if (bean == null)
			return sb.append("}").toString();
		Method[] ms = bean.getClass().getMethods();
		Method m = null;
		for (int i = 0; i < ms.length; i++) {
			m = ms[i];
			if (m.getName().startsWith("get")) {
				try {
					Object o = m.invoke(bean);
					sb.append("'");
					sb.append(StringUtil.firstLower(m.getName().substring(3)));
					sb.append("' : '");
					sb.append(o == null ? "" : o);
					sb.append("'");
					if (i < ms.length - 1)
						sb.append(",");
				} catch (Exception e) {
					// e.printStackTrace();
					continue;
				}
			}
		}
		return sb.toString();
	}

	public static <T> String list2Json(List<T> list) {
		StringBuilder sb = new StringBuilder("{");
		if (list == null || list.size() == 0)
			return sb.append("}").toString();
		T t;
		Method[] ms = null;
		Method m = null;
		Object o = null;
		sb.append("'total':");
		sb.append(list.size());
		sb.append(",'rows':[");
		for (int i = 0; i < list.size(); i++) {
			sb.append("{");
			t = list.get(i);
			ms = t.getClass().getMethods();
			for (int j = 0; j < ms.length; j++) {
				m = ms[j];
				if (m.getName().startsWith("get")) {
					try {
						o = m.invoke(t);
						sb.append("'");
						sb.append(StringUtil.firstLower(m.getName().substring(3)));
						sb.append("' : '");
						sb.append(o == null ? "" : o);
						sb.append("'");
						if (j < ms.length - 1)
							sb.append(",");
					} catch (Exception e) {
						// e.printStackTrace();
						continue;
					}
				}
			}
			sb.append("}");
			if (i < list.size() - 1)
				sb.append(",");
		}
		sb.append("]}");
		return sb.toString();
	}

}
